package com.peans.common.utils.mapBean;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.Map;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

/**
 * Created by res-miaofeng on 2016/3/2.
 */
public class MapBeanJsonSerializer extends JsonSerializer<MapBean> {

    @Override
    public void serialize(MapBean bean, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
        jgen.writeStartObject();
        if (!bean.isEmpty()){
            for (Map.Entry<BeanProperty,Object> e : bean.entrySet()) {
                BeanProperty p = e.getKey();
                Object value = e.getValue();
                if (p.getClassType().equals(MapBean.class)){
                    jgen.writeObjectField(p.getName(),(MapBean)value);
                }else {
                    write(jgen,p,value);
                }
            }
        }
        jgen.writeEndObject();
    }

    private static void write(JsonGenerator jgen,BeanProperty p, Object object){
        try {
            Class<?> type = p.getClassType();
            if (type.equals(String.class)){
                jgen.writeStringField(p.getName(),(String)object);
            }else if (type.equals(Boolean.class) || type.equals(Boolean.TYPE)){
                jgen.writeBooleanField(p.getName(),(Boolean)object);
            }else if (type.equals(Integer.class) || type.equals(Integer.TYPE)){
                jgen.writeNumberField(p.getName(),(Integer)object);
            }else if (type.equals(Long.class) || type.equals(Long.TYPE)){
                jgen.writeNumberField(p.getName(),(Long)object);
            }else if (type.equals(Double.class) || type.equals(Double.TYPE)){
                jgen.writeNumberField(p.getName(),(Double)object);
            }else if (type.equals(Float.class) || type.equals(Float.TYPE)){
                jgen.writeNumberField(p.getName(),(Float)object);
            }else if (type.equals(BigDecimal.class)){
                jgen.writeNumberField(p.getName(),(BigDecimal)object);
            }else if (type.equals(byte[].class)){
                jgen.writeBinaryField(p.getName(),(byte[])object);
            }else {
                jgen.writeObjectField(p.getName(),object);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
